require(['grid', 'topBar', 'select2'], function () {
    var mapDistriDialog,
        editDialog,
        funName,
        lineIds,
        lineInfo,
        firstInit = true,
        $top = $('#top'),
        $grid = $('#grid1'),
        $historyGrid = $('#grid2');//历史明细

    //顶部栏初始化
    function topBarInit() {
        $top.topBar({
            left: [
                {
                    text: '黑点名称',
                    name: 'blackName',
                    width: 160,
                    type: 'text'
                },
                {
                    text: '启用状态',
                    name: 'blackSt',
                    type: 'select',
                    width: 100,
                    showEmpty: false,// 不显示“请选择”
                    data: [
                        {value: '', text: '全部'},
                        {value: 1, text: '启用'},
                        {value: 0, text: '停用'}
                    ]
                },
                {
                    text: '查询',
                    type: 'btn',
                    click: function () {
                        reloadGridData();
                    }
                },
                {
                    text: '黑点分布地图',
                    type: 'btn',
                    css: 'map-btn',
                    click: function () {
                        if (check2()) {
                            var option = {};
                            option.title = '黑点分布地图';
                            getMapDistriDialog(option).dialog('exec', 'showData', lineInfo);
                        }
                    }
                }

            ],
            right: [
                {
                    text: '导出',
                    type: 'export-btn',
                    authority: '',
                    item: [
                        {
                            text: 'Excel导出',
                            click: function () {
                                exportFile('Excel');
                            }
                        },
                        {
                            text: 'PDF导出',
                            click: function () {
                                exportFile('Pdf');
                            }
                        }
                    ]
                },
                {
                    text: '+分配黑点',
                    type: 'btn',
                    width: '698',
                    authority: '',
                    click: function () {
                        distributeBlackSpot();
                    }
                }
            ]
        });
    }

    //grid初始化
    function gridInit() {
        function dangerFormat(value) {
            var html = '<span class="dangerous-setting">';
            switch (value) {
                case 1:
                    html += '<span class="active"></span><span></span><span></span><span></span><span></span>';
                    break;
                case 2:
                    html += '<span class="active"></span><span class="active"></span><span></span><span></span><span></span>';
                    break;
                case 3:
                    html += '<span class="active"></span><span class="active"></span><span class="active"></span><span></span><span></span>';
                    break;
                case 4:
                    html += '<span class="active"></span><span class="active"></span><span class="active"></span><span class="active"></span><span></span>';
                    break;
                case 5:
                    html += '<span class="active"></span><span class="active"></span class="active"><span></span class="active"><span></span><span class="active"></span>';
                    break;
                default :
                    html += '<span></span><span></span><span></span><span></span><span></span>';
                    break;
            }
            html += '</span>';
            return html;
        }

        function blackStFormat(value) {
            if (value == '0') {
                return '停用';
            } else {
                return '启用';
            }
        }

        $grid.grid({
            url: "/baseLineBlackRel/searchBaseLineBlackRelPage.htm",
            colModel: [
                {name: "relId", label: 'relId', key: true, hidden: true},
                {name: "lineName", label: '线路名称'},
                {name: "blackName", label: '黑点名称'},
                {name: "dangerDegree", label: '黑点危险度', align: 'center', formatter: dangerFormat, width: 115},
                {name: "blackSt", label: '状态', width: 70, formatter: blackStFormat},
                {name: "mnpltDate", label: '启用/停用日期', width: 100},
                {
                    name: "operate", width: 130, label: '操作', title: false, align: 'center',
                    formatter: 'operArea',
                    formatoptions: [{
                        text: '开启',
                        css: 'operate-start',
                        rule: function (rowData) {
                            return rowData.blackSt === '0';
                        },
                        click: function (data) {
                            openCloseLineBlackRel(data.relId);
                        }
                    }, {
                        text: '关闭',
                        css: 'operate-stop',
                        rule: function (rowData) {
                            return rowData.blackSt === '1';
                        },
                        click: function (data) {
                            openCloseLineBlackRel(data.relId);
                        }
                    }, {
                        text: '历史',
                        css: 'operate-history',
                        click: function (data) {
                            reloadHistoryGrid(data.relId);
                        }
                    }]

                }
            ],
            height: 235,
            multiselect: false
        });

        $historyGrid.grid({
            url: "/baseLineBlackRelHis/searchBaseLineBlackRelHisPage.htm",
            colModel: [
                {name: "relId", label: 'relId', key: true, hidden: true},
                {name: "lineName", label: '线路名称'},
                {name: "blackName", label: '黑点名称'},
                {name: "dangerDegree", label: '黑点危险度', align: 'center', formatter: dangerFormat, width: 115},
                {name: "strtusDate", label: '启用日期'},
                {name: "dsablDate", label: '停用日期'},
                {name: "strtusDura", label: '启用时长（天）'}
            ],
            height: 235,
            multiselect: false
        });
    }

    /**
     * 获取地图分布对话框，如果没有就先创建
     * @param option {object} 对话框配置
     * @returns {jQuery}
     */
    function getMapDistriDialog(option) {
        option = option || {};
        if (mapDistriDialog) {
            mapDistriDialog.dialog('open');
            if (option.title) {
                mapDistriDialog.dialog('setOption', 'title', option.title);
            }
        } else {
            mapDistriDialog = $('<div>').dialog({
                title: option.title || '地图分布',
                url: './safety/setting/funBlackspotMap2.htm',
                height: $(window.parent).height() * 0.9,
                width: $(window.parent).width() * 0.9,
                autoOpen: true,
                buttons: []
            });
        }
        return mapDistriDialog;
    }

    /**
     * 获取表单对话框，如果没有就先创建
     * @param option {object} 对话框配置
     * @returns {jQuery}
     */
    function getEditDialog(flag, option) {
        funName = flag;
        option = option || {};
        if (editDialog) {
            editDialog.dialog('open');
            if (option.title) {
                editDialog.dialog('setOption', 'title', option.title);
            }
        } else {
            editDialog = $('<div>').dialog({
                title: option.title || '分配黑点',
                url: './safety/setting/funLineBlackspotSetEdit.htm',
                height: $(window.parent).height() * 0.9,
                width: 720,
                autoOpen: true,
                buttons: [
                    {
                        text: '确定',
                        css: 'mr10',
                        click: function () {
                            var _t = this;
                            $(_t).dialog('exec', funName, function () {
                                reload(true);
                            });
                        }
                    },
                    {
                        text: '取消',
                        css: 'btn-cancel',
                        click: function () {
                            $(this).dialog('close');
                        }
                    }
                ]
            });
        }
        return editDialog;
    }

    //查询grid
    function reloadGridData() {
        //准备条件参数
        var postData = $top.getValues();

        if (check1()) {
            postData.orgIds = lineIds;

            //console.log(postData);

            $grid.grid('setGridParam', {
                datatype: "JSON",
                page: 1,
                postData: postData
            }).trigger("reloadGrid");
        }
    }

    //查询historyGrid
    function reloadHistoryGrid(relId) {
        $historyGrid.grid('setGridParam', {
            datatype: "JSON",
            page: 1,
            postData: {'relId': relId}
        }).trigger("reloadGrid");
    }

    //开启或关闭
    function openCloseLineBlackRel(relId) {
        $.ajaxExt({
            url: "/baseLineBlackRel/openCloseLineBlackRelById.htm",
            data: {'relId': relId}
        }).done(function (data) {
            reloadGridData();
        });
    }

    //选择一条线路进行黑点分配
    function distributeBlackSpot() {
        if (check2()) {
            var option = {};
            option.title = '给“' + lineInfo.name + '”分配黑点';
            getEditDialog('distribute', option).dialog('exec', 'reloadBlackGridData');
        }
    }

    //检查左侧树是否勾选
    function check1() {
        if (!firstInit) {
            var nodes = commonFun.getLeftTreeCheckedNodes('LINE');
            if (nodes && nodes.length > 0) {
                lineIds = nodes.toString();
                return true;
            } else {
                $.messager.alert("警告", "请先选择线路", "info");
                return false;
            }
        }
        firstInit = false;
    }

    //检查左侧树是否勾选
    function check2() {
        var nodes = commonFun.getLeftTreeCheckedNodes('LINE', true);
        if (nodes && nodes.length == 1) {
            lineInfo = nodes[0];
            return true;
        } else {
            $.messager.alert("警告", "仅选择一条线路", "info");
            return false;
        }
    }

    //导出
    function exportFile(suffix) {
        if ($grid.getGridParam("reccount") > 0) {
            //准备条件参数
            var postData = $top.parent().getValues();
            postData.orgIds = lineIds;
            $.exportFile("/baseLineBlackRel/exportBaseLineBlackRel" + suffix + ".htm", postData);
        } else {
            $.messager.alert("警告", "请先查询数据！", "info");
        }
    }

    //新增修改后执行
    function reload(close) {
        reloadGridData();
        close && editDialog.dialog('close');
    };

    topBarInit();
    gridInit();

    //进页面后查询
    reloadGridData();
});